from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAdminUser
from datetime import date, timedelta

from goods.models import GoodsVisitCount
from meiduo_admin.serializers.serializers import GoodsVisitCountSerializer
from users.models import User


class UserTotalCountView(APIView):

    permission_classes = [IsAdminUser]
    def get(self,request):
        now_date = date.today()
        count = User.objects.all().count()
        return Response({
            'date':now_date,
            'count':count
        })


class UserDayCountView(APIView):

    permission_classes = [IsAdminUser]
    def get(self,request):
        now_date = date.today()
        count = User.objects.filter(date_joined__gte=now_date).count()
        return Response({
            'date':now_date,
            'count':count
        })
class UserActiveCountView(APIView):
    permission_classes = [IsAdminUser]
    def get(self,request):
        now_date = date.today()
        count = User.objects.filter(last_login__gte=now_date).count()
        return Response({
            'date': now_date,
            'count': count
        })


class UserOrderCountView(APIView):
    # 指定管理员权限
    permission_classes = [IsAdminUser]
    def get(self,request):
        now_date = date.today()
        count = len(set(User.objects.filter(orders__create_time__gte=now_date)))
        return Response({
            'date': now_date,
            'count': count
        })

class UserMonthCountView(APIView):
    # 指定管理员权限
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取当前日期
        now_date = date.today()
        start_date = date.today()-timedelta(days=29)
        date_list=[]
        for i in range(30):
            # 循环遍历获取当天日期
            index_date = start_date + timedelta(days=i)
            # 指定下一天日期
            cur_date = start_date + timedelta(days=i + 1)
            # 查询条件是大于当前日期index_date，小于明天日期的用户cur_date，得到当天用户量
            count = User.objects.filter(date_joined__gte=index_date,date_joined__lt=cur_date).count()
            date_list.append({
                'count':count,
                'date':index_date
            })
        return Response(date_list)


class GoodsDayView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取当前日期
        now_date = date.today()
        goods = GoodsVisitCount.objects.filter(date__gte=now_date)
        ser = GoodsVisitCountSerializer(goods,many=True)

        return Response(ser.data)